#include "vcf.h"
#include "util.h"

#include <iostream>
#include <assert.h>


void Vcf::Load(istream &input){

	string line;
	Vcard vcard;

	while(true){
		do{
			if(input.eof()){
				return;
			}
			getline(input, line);
		}while(line.compare(this->BEGIN_CARD) != 0);

		vcard.Clear();
		while(!input.eof()){
			getline(input, line);
			if( line.compare(this->END_CARD) == 0){
				break;
			}
			vcard.InsertLine(line);
		}
		string name = vcard.GetName();
		assert( !name.empty() );
		vcards[name].InsertVcard(vcard);
	}
}

void Vcf::Write(ostream &output){
	
	for(hash_map<string, Vcard>:: iterator iter = this->vcards.begin(); iter != this->vcards.end(); iter++)
	{
		bool hasImage = false;
		bool skip	 = false;

		Vcard vcard = iter->second;
		output << this->BEGIN_CARD << endl;
		for(int i=0; i< vcard.GetCount(); i++)
		{
			string &line = vcard.GetLine(i);

			if(skip && Util::StringStartWith(line, "\t")){
				continue;
			}
			else{
				skip = false;
			}


			if(Util::StringStartWith(line, "PHOTO;")){
				if(hasImage){
					skip = true;
					continue;
				}
				else{
					hasImage = true;
				}
			}

			if(Util::StringStartWith(line, "EMAIL;TYPE=INTERNET:") && line.find('@') == string::npos ){
				output << line << "@qq.com" << endl;
			}
			else{
				output <<  line << endl;
			}
		}
		output << this->END_CARD << endl;
	}

}

Vcf::Vcf(void):BEGIN_CARD("BEGIN:VCARD"),END_CARD("END:VCARD")
{
}

Vcf::~Vcf(void)
{
}
